<!-- 被申请人答复 -->
<template>
  <div class="file_part">
    <div style="margin-right: 20px">
      <a-table :columns="columns" :data-source="tableList" rowKey="id" :pagination="false" :loading="loading" bordered>
        <span slot="name" slot-scope="text, record" class="overBox">
          <div class="beyond_hiding">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ record.name + (record.agenter ? '-' + record.agenter : '') + (record.phone ? '-' + record.phone : '') }}</span>
              </template>
              {{ text }}
            </a-tooltip>
          </div>
        </span>
        <span slot="attachmentList" slot-scope="list, record, rIndex" style="text-align: left;">
          <div v-if="list && list.length">
            <div v-for="item in list" :key="item.id">
              <div v-if="item.fileList">
                <a v-for="file in item.fileList" :key="file.id" class="file-css">
                  <div style="width: 100%; display: flex; align-items: center">
                    <span @click="fileView(file)" :title="file.name" class="beyond_hiding">
                      <a-icon type="folder" theme="filled" />
                      {{ file.name }}
                    </span>
                  </div>
                </a>
              </div>
            </div>
          </div>
          <div v-else>未上传附件</div>
        </span>
        <span slot="operation" slot-scope="text, record">
          <template>
            <div class="flex_center_div">
              <div @click="downloadMaterialAll" style="margin-right: 10px;" class="cursor_pointer">
                <a-icon type="download" style="margin-right: 8px;color: #1890ff;"/>
                <a>下载</a>
              </div>
              <div v-if="record.phone && record.name && category == 'evidence'" class="flex_center_div">
                <a-divider type="vertical" />
                <a-popconfirm title="确定发送吗？" @confirm="() => sendMessage(record)">
                  <div class="button_flex cursor_pointer flex_center_div">
                    <img src="~@/assets/images/accept/send.svg" style="width:14px;height: 14px;margin-right: 10px;" />
                    <a class="download_div">发送</a>
                  </div>
                </a-popconfirm>
              </div>
            </div>
          </template>
        </span>
      </a-table>
    </div>
  </div>
</template>
<script>
import { APP_USER, APP_DEPT } from '@/store/mutation-types.js'
import storage from 'store'
import { getTargetListByApplyid } from '@/api/accept/apl_target'
import { sendTargetMessage } from '@/api/supervise/apl_supervise.js'
import { kkfilePreview, downloadFile } from '@/utils/util.js'
import { updateFilename } from '@/api/accept/aprv_materials_options'
import { downloadMaterialAll, queryMatterAttachList } from '@/api/apply/apl_matter_attach'

// 默认当前的类型是被申请人回复类型
export default {
  props: {
    applyid: {
      type: String,
      required: true
    },
    isEditModel: {
      type: Boolean,
      required: true
    },
    category: {
      type: String,
      required: false
    }
  },
  data () {
    return {
      currentUser: storage.get(APP_USER),
      operateBtnDisabled: true, // 特殊情况限制按钮
      targetOrgData: [], // 组织树层级数据
      selectPersons: undefined, // 选中的人员
      // selectPersonsIds: [],
      btnDisabled: true,
      materialList: [], // 材料list
      fileList: [], // 文件列表
      loading: false, // 加载框
      clickTimeout: undefined,
      newFilename: '',

      columns: [
        {
          title: '被申请人',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
          width: '20%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '申请人申请材料',
          dataIndex: 'materialList',
          width: '60%',
          align: 'center',
          key: 'materialList',
          scopedSlots: { customRender: 'attachmentList' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '200px',
          align: 'center',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      tableList: [] // 表格数据
    }
  },
  components: {},
  created () {
    if (this.applyid) {
      this.queryFileData()
    }
  },
  mounted () {},
  watch: {
    selectPersons: {
      handler (val) {
        this.btnDisabled = true
        if (this.selectPersons && this.selectPersons.length > 0) {
          let targetOrg = []
          this.selectPersons.forEach(person => {
            const target = this.targetOrgData.filter(el => el.id == person)
            targetOrg = targetOrg.concat(target)
          })
          const hasPhone = !targetOrg.some(el => !el.phone)
          if (hasPhone) {
            if (this.materialList && this.materialList.length > 0) {
              let validate = true
              this.materialList.forEach(el => {
                if (el.require == 3200 && !(el.fileList && el.fileList.length > 0)) {
                  validate = false
                }
              })
              if (validate) {
                this.btnDisabled = false
              }
            }
          }
        } else {
          this.btnDisabled = true
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 查询赣政通的组织机构
    async queryFileData () {
      await this.getTargetOrg()
      await this.queryList()
      this.tableList = []
      if (this.targetOrgData && this.materialList) {
        this.targetOrgData.forEach(el => {
          const tableObj = JSON.parse(JSON.stringify(el))
          tableObj.materialList = this.materialList
          this.tableList.push(tableObj)
        })
      }
    },
    async getTargetOrg () {
      const res = await getTargetListByApplyid(this.applyid)
      if (res.code === 0) {
        this.targetOrgData = res.data ? res.data : []
      } else {
        this.$message.error('查询组织机构异常')
      }
    },
    async queryList () {
      this.loading = true
      const res = await queryMatterAttachList({ applyid: this.applyid }).finally(() => {
        this.loading = false
      })
      if (res.data && res.data.length) {
        this.materialList = res.data
        if (this.materialList && this.materialList.length > 0) {
          this.materialList.forEach(el => {
            el.isEditor = false
          })
        }
      } else {
        this.$message.error('查询被申请人材料异常')
      }
    },
    // 附件在线预览
    fileView (file) {
      console.log('文件预览', file)
      window.open(kkfilePreview(file.url))
    },
    downloadMaterialAll () {
      this.$confirm({
        title: '提示',
        content: '确定下载所有的材料附件吗？',
        onOk: () => {
          this.$message.loading({
            content: '材料下载中...',
            key: 'fileDownload',
            duration: 0
          })
          downloadMaterialAll({ applyid: this.applyid })
            .then(res => {
              downloadFile(res, this.applyid + '.zip')
              this.$message.success({
                content: '材料下载成功',
                key: 'fileDownload',
                duration: 2
              })
            })
            .catch(function (err) {
              console.log(err)
            })
        }
      })
    },
    sendMessage (record) {
      this.$confirm({
        title: '提示',
        content: '是否发送赣政通待办',
        onOk: () => {
          let targetOrg = []
          const target = this.targetOrgData.filter(el => el.id == record.id)
          targetOrg = targetOrg.concat(target)
          const hasPhone = !targetOrg.some(el => !el.phone)
          if (!hasPhone) {
            this.$message.error('被申请人电话为空')
            return
          }
          const phones = targetOrg.map(el => el.phone)
          this.loading = true
          const savem = this.$message.loading('正在发送中...', 0)
          sendTargetMessage(this.applyid, this.currentUser.userId, phones)
            .then(res => {
              console.log('res', res)
              if (res.code !== 0) {
                this.$message.error('发送赣政通待办失败')
              } else {
                this.$message.success('发送赣政通待办成功')
              }
            })
            .finally(() => {
              this.loading = false
              setTimeout(savem, 0)
            })
        }
      })
    },
    handleDoubleClick (fileItem, index) {
      // 将材料名先复制给 newFilename 双向绑定到 编辑框上
      this.newFilename = fileItem.filename
      fileItem.isEditor = true // 进入编辑模式
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs[`input${index}`].forEach(e => {
          e.focus()
        })
      })
    },
    saveFileName (fileItem) {
      // 保存文件名的逻辑
      fileItem.filename = this.newFilename
      updateFilename(fileItem.id, fileItem.filename).then(res => {
        if (res.code == 0) {
          this.$set(fileItem, 'fileName', this.newFilename)
          this.$set(fileItem, 'isEditor', false)
        } else {
          this.$message.error('修改文件名称错误')
        }
      })
    },
    // 在 saveFileName 方法中更新文件名并退出编辑模式
    handleClick (fileItem, index) {
      // 模拟双击事件
      if (this.clickTimeout) {
        clearTimeout(this.clickTimeout)
        this.clickTimeout = null
        this.handleDoubleClick(fileItem, index)
      } else {
        this.clickTimeout = setTimeout(() => {
          this.clickTimeout = null
          this.fileView(fileItem)
        }, 300) // 这里的时间间隔可以根据实际情况调整
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import '~@/assets/css/apply/caseProcedure.scss';
</style>

<style lang="less" scoped>
.file_list {
  min-height: 200px;
}

.file_icon {
  font-size: 25px;
}

.file_button {
  display: inline-block;
  margin-right: 20px;
}

.customer_div {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 20px;
}

.customer_span {
  width: 60px;
  font-size: 18px;
}

.customer_input {
  width: 400px;
}

.customer_icon_group {
  margin-left: 30px;
}

.customer_icon {
  font-size: 18px;
  cursor: pointer;
}

.upload-style {
  padding-left: 450px;

  .ant-btn:not([disabled]):hover {
    text-decoration: none;
    margin-left: 0px;
  }

  .ant-upload.ant-upload-select {
    margin-left: 200px;
  }
}

.upload-style-hidden {
  padding-left: 320px;

  .ant-btn:not([disabled]):hover {
    text-decoration: none;
    margin-left: 0px;
  }

  .ant-upload.ant-upload-select {
    margin-left: 200px;
  }

  ::v-deep .ant-upload-list-item-card-actions {
    display: none;
  }
}

.div_center {
  display: flex;
  /*开启flex布局*/
  justify-content: center;
  /*水平居中*/
  align-items: center;
  /*垂直居中*/
  height: 100%;
  /*设置高度*/
}

.progress_success_btn {
  margin-right: 150px;
}

.progress_fail_btn {
  margin-left: 150px;
}

.add_form_btn {
  display: block;
  float: right;
  margin-right: 20px;
}

.add_form_label {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

::v-deep .ant-upload-list-text {
  width: 550px;
}
::v-deep .ant-form-item-label {
  > label {
    font-size: 16px;
  }
}

.transparent-input {
  background-color: transparent; /* 设置背景透明 */
  border: none; /* 移除边框 */
  border-bottom: 1px solid rgb(251, 251, 252); /* 可选：添加底部边框以提升可视度 */
  outline: none; /* 移除默认的输入框外观 */
  color: rgb(119, 166, 253); /* 设置文本颜色 */
  /* 可以根据需要添加更多样式 */
}

.file_part {
  margin: 16px 0px 32px 0px;
  ::v-deep .ant-table-thead > tr > th {
    background: #f2f8fc;
    // color: red;
  }
  ::v-deep .ant-table-column-title {
    font-weight: bold;
  }
}

.flex_center_div {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
